<?php
class Service_Model_EduDic
{
    /**
     * Web scrap a request to edu.xunta.es dictionary
     * 
     * @param string $q
     * @return string
     */
    public function query($q)
    {
        $client = new Zend_Http_Client('http://www.edu.xunta.es/diccionarios/BuscaTermo.jsp',
            array(
                'maxredirects' => 0,
                'timeout'      => 30
            )
        );
        
        // Method via POST
        $client->setMethod(Zend_Http_Client::POST);
        
        $client->setParameterPost(array(
            'TermoK'  => $q,
            'Termo'   => $q,
        ));
        
        $response = $client->request();
        $html = $response->getBody();
        
        $dom = new Zend_Dom_Query($html);
        $results = $dom->queryXpath('//tr[14]/td');
        
        $count = count($results); 
        
        if($count != 1) {
            return null;
        }                
        
        $sx = simplexml_import_dom ($results->current());
        $html = trim($sx->asXML());
        
        // remove td tag
        $html = preg_replace('/&amp;nbsp[;]?/', ' ', $html);
        $html = preg_replace('/^<td[^>]*>/', '', $html);
        $html = preg_replace('/<\/td>$/', '', $html);
        
        $text = trim( html_entity_decode(strip_tags($html, '<a><div><p><em><i><b><strong>'), ENT_COMPAT, 'UTF-8') );
        // http://www.edu.xunta.es/diccionarios/ListaDefinicion.jsp?IDXT=16233
        if(preg_match('/ href="ListaDefinicion\.jsp/', $text)) {
            $text = str_replace(' href="ListaDefinicion.jsp',
                                ' target="_blank" href="http://www.edu.xunta.es/diccionarios/ListaDefinicion.jsp',
                                $text);
        }
        
        if($text=='') {
            return null;
        }
        
        return $text;
    }        
}
